package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户相关接口")
@RequestMapping("users")
@RequiredArgsConstructor
@RestController
public class UserController {
    private final UserService userService;
//    1.新增用户
    @PostMapping
    @ApiOperation("用户新增")
    public void save(@RequestBody UserFormDTO userFormDTO){
        User user=BeanUtil.copyProperties(userFormDTO, User.class);
        userService.save(user);
    }
//    2.删除用户
    @DeleteMapping("/{id}")
    @ApiOperation("用户删除")
    public void delete(@PathVariable("id") Long id){
        userService.removeById(id);
    }
//    3.根据id查询用户
@GetMapping("/{id}")
@ApiOperation("根据id查询用户")
public UserVO queryUserById(@PathVariable("id") Long userId){
    // 基于自定义service方法查询
    return userService.queryUserAndAddressById(userId);
}
//    4.根据id批量查询
    @GetMapping()
    @ApiOperation("用户批量查询")
    public List<UserVO> listByIds(@ApiParam("用户id集合")@RequestParam ("ids") List<Long> ids){
        final List<User> users = userService.listByIds(ids);
        return BeanUtil.copyToList(users, UserVO.class);
    }
//    5.根据id扣减余额
    @ApiOperation("用户余额扣减")
    @PutMapping("/{id}/deduction/{money}")
    public void deductionBalance(@ApiParam("用户id") @PathVariable("id") Long id, @PathVariable("money") Integer money){
        userService.deductBalance(id, money);
        userService.lambdaUpdate()
                .setSql("balance=balance-" + money)
                .eq(User::getId, id)
                .update();
    }
    //    4.条件查询name\status\minbalance\maxbalance
    @GetMapping("/list")
    @ApiOperation("复杂条件查询")
    public List<UserVO> queryUsers(UserQuery userQuery){
        final List<User> users = userService.qurtyUsers(userQuery.getName(), userQuery.getStatus(), userQuery.getMinBalance(), userQuery.getMaxBalance());
        return BeanUtil.copyToList(users, UserVO.class);
    }
//    5.分页查询
    @GetMapping("/page")
    @ApiOperation("分页查询")
    public PageDTO<UserVO> queryUserpage(UserQuery userQuery){
        return userService.queryUserpage(userQuery);
    }
}
